// 图片消息组件
import React, { useEffect, useCallback } from "react";
import PreviewPic from "./PreviewPic";

interface PicMessageProps{
    data: NewMsg;
    scrollBottom: () => void;
};

function PicMessage(props: PicMessageProps){
    const scrollBottom = props.scrollBottom;
    const { isSelf, msg, filename, user } = props.data;
    var [picSrc, setPicSrc] = React.useState<string>("");
    var [targetId] = React.useState<string>('' + Math.floor(Math.random() * 1000) + Date.now());
    useEffect(() => {
        let res: File;
        if(Object.prototype.toString.call(msg) === "[object ArrayBuffer]"){
            res = new File([msg as ArrayBuffer], filename);
        }else   res = msg as File;
        setPicSrc(window.URL.createObjectURL(res));
    },[msg, filename]);

    // 图片加载出来之后滚动容器
    const handleImgLoad = useCallback(() => {
        scrollBottom();
    }, [scrollBottom]);

    return (
        <div className={isSelf ? "text-right pl-2 pr-2" : "text-left pl-2 pr-2"}>
            <div className="text-primary pb-1">{ user }</div>
            <div 
                className={isSelf ? "alert alert-danger text-justify p-2" : "alert alert-info text-justify p-2"} 
                role="alert" 
                style={{display: "inline-block", maxWidth: "40%", minHeight: '42px'}}
            >
                <img 
                    role="button"
                    onLoad={ handleImgLoad }
                    data-toggle="modal" data-target={`#previewBigPic${targetId}`}
                    style={{maxWidth: "100%", cursor: "pointer"}} 
                    src={picSrc} alt="图片出错了>_<" 
                />
            </div>

            <PreviewPic targetId={targetId} picSrc={picSrc} />
        </div>
    );
}

export default PicMessage;